package com.ylzinfo.answer.controller;

import com.github.pagehelper.PageInfo;
import com.ylzinfo.answer.bean.DicCodeBean;
import com.ylzinfo.answer.dto.FormDTO;
import com.ylzinfo.answer.dto.TableDTO;
import com.ylzinfo.answer.service.DicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/dic")
public class DicController {

    @Autowired
    private DicService dicService;

    @GetMapping("/library")
    public String library() {
        return "question/library";
    }

    @GetMapping("/list")
    public String list() {
        return "system/dic_list";
    }

    @GetMapping(value = {"form/{id}", "form"})
    public String form(@PathVariable(required = false) Integer id, Model model) {
        model.addAttribute("id", id);
        return "system/dic_form";
    }

    @GetMapping("/getByAnswerType")
    @ResponseBody
    public PageInfo<DicCodeBean> getByAnswerType(int page, int limit, String answerType) {
        return dicService.getByAnswerType(page, limit, answerType);
    }

    @GetMapping("/getByFields")
    @ResponseBody
    public TableDTO<List<DicCodeBean>> getByCode(int page, int limit, DicCodeBean dicCodeBean) {
        PageInfo<DicCodeBean> pageInfo = dicService.getByFields(dicCodeBean, page, limit);
        return new TableDTO<List<DicCodeBean>>().dataSuccess(pageInfo.getList(), (int) pageInfo.getTotal());
    }

    @PostMapping("/add")
    @ResponseBody
    public FormDTO add(DicCodeBean dicCodeBean) {
        if (dicService.insert(dicCodeBean)) {
            return new FormDTO().success("新增成功");
        }
        return new FormDTO().fail("新增失败");
    }

    @PostMapping("/delete")
    @ResponseBody
    public FormDTO delete(DicCodeBean dicCodeBean) {
        dicService.delete(dicCodeBean.getList());
        return new FormDTO().success("删除成功");
    }

    @GetMapping("/get/{id}")
    @ResponseBody
    public DicCodeBean getById(@PathVariable long id) {
        return dicService.findById(id);
    }

    @PostMapping("/update")
    @ResponseBody
    public FormDTO update(DicCodeBean dicCodeBean) {
        if (dicService.update(dicCodeBean)) {
            return new FormDTO().success("修改成功");
        }
        return new FormDTO().fail("修改失败");
    }
}
